<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class UsersAssetsLog extends Model
{
    protected $table = 'users_assets_log_01';
    public $tableStr = 'users_assets_log_';
    public $timestamps = false; // 指示模型是否自动维护时间戳
    protected $dateFormat = 'U'; // 模型日期列的存储格式。

    protected function tables(){
        return array(
            'users_assets_log_01',
            'users_assets_log_02',
            'users_assets_log_03',
            'users_assets_log_04',
            'users_assets_log_05',
            'users_assets_log_06',
        );
    }

    /**
     * Todo:: 获取表名称
     * @param $userId
     * @return bool|int|string
     */
    public function tableName($userId){
        $num = $userId%6;
        $string = $this->tableStr;
        if($num == 0){
            $string .= '06';
        }elseif($num>0 && $num < 10){
            $string .= '0'.$num;
        }elseif($num > 10){
            $string .= $num;
        }
        if(in_array($string,$this->tables())){
            $this->table = $string;
            return $string;
        }
        return false;
    }

    /**
     * Todo:: 属性
     * @param $code
     * @return array|mixed|null
     */
    public function typeArr($code=''){
        $data = [
            'create' => '创建',
            'update' => '更新',
        ];
        if($code && isset($data[$code])){
            return $data[$code];
        }
        return $data;
    }

    /**
     * Todo:: 资产类型
     * @param $code
     * @return array|mixed|null
     */
    public function assetsType($code=''){
        $data = [
            'total' => '总值',
            'available' => '可用值',
            'freeze' => '冻结值',
        ];
        if($code && isset($data[$code])){
            return $data[$code];
        }
        return $data;
    }

    /**
     * Todo:: 变动属性
     * @param $code
     * @return array|mixed|null
     */
    public function changeType($code=''){
        $data = [
            0 => '未知',
            1 => '增加',
            2 => '减少',
        ];
        if($code && isset($data[$code])){
            return $data[$code];
        }
        return $data;
    }


    /**
     * Todo:: 添加用户记录信息
     * @param $userId
     * @param $data
     * @return int
     */
    public function addData($userId,$data){
        $this->tableName($userId);
        $insert = DB::table($this->table)->insertGetId([
            'user_id' => $userId,
            'type' => isset($data['type'])?$data['type']:'not',
            'assets_name' => isset($data['assets_name'])?$data['assets_name']:'not',
            'assets_type' => isset($data['assets_type'])?$data['assets_type']:'not',
            'change_type' => isset($data['change_type'])?$data['change_type']:0,
            'before_value' => isset($data['before_value'])?$data['before_value']:0,
            'change_value' => isset($data['change_value'])?$data['change_value']:0,
            'after_value' => isset($data['after_value'])?$data['after_value']:0,
            'explanation' => isset($data['explanation'])?$data['explanation']:'',
            'remark' => isset($data['remark'])?$data['remark']:'',
        ]);
        return $insert;
    }

    /**
     * Todo:: 创建多个数据
     * @param $userId
     * @param $data
     * @return bool
     */
    public function insertData($userId,$data){
        $this->tableName($userId);
        $insert = DB::table($this->table)->insert($data);
        return $insert;
    }


    /**
     * Todo:: 获取用户资产日志
     * @param $userId
     * @param array $conditions
     * @param int $page
     * @param int $pageSize
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Database\Query\Builder
     */
    public function userLists($userId,$conditions=[],$page=1,$pageSize=10){
        $this->tableName($userId);
        $lists = DB::table($this->table)->where('user_id',$userId);
        if (isset($conditions['assets_name']) && !empty($conditions['assets_name'])) {
            $lists->where('assets_name', $conditions['assets_name']);
        }
        if (isset($conditions['assets_type']) && !empty($conditions['assets_type'])) {
            $lists->where('assets_type', $conditions['assets_type']);
        }
        if (isset($conditions['change_type']) && !empty($conditions['change_type'])) {
            $lists->where('change_type', $conditions['change_type']);
        }
        if (isset($conditions['start_time']) && !empty($conditions['start_time']) && isset($conditions['end_time']) && !empty($conditions['end_time'])) {
            $lists->whereBetween('created_at', [$conditions['start_time'],$conditions['end_time']]);
        }else{
            if(isset($conditions['start_time']) && !empty($conditions['start_time'])){
                $lists->where('created_at','>',$conditions['start_time']);
            }elseif(isset($conditions['end_time']) && !empty($conditions['end_time'])){
                $lists->where('created_at','<',$conditions['end_time']);
            }
        }
        $lists = $lists->orderBy('created_at','desc')->paginate($pageSize,['*'],'page',$page);
        return $lists;
    }

    /**
     * Todo:: 全部需要的表
     * @param array $conditions 条件
     * @param array $select 查询结果
     * @return \Illuminate\Database\Query\Builder|mixed
     */
    private function allTable($conditions=[],$select=[]){
        $lists = DB::table($this->table);
        $lists = $this->allWhere($lists,$conditions);
        $lists = $this->allSelect($lists,$select);
        $tables = $this->tables();
        unset($tables[0]);
        foreach ($tables as $key=>$val){
            $rowTable = DB::table($val);
            $rowTable = $this->allWhere($rowTable,$conditions);
            $rowTable = $this->allSelect($rowTable,$select);
            $lists->union($rowTable);
        }
        return $lists;
    }

    /**
     * Todo:: 全部资产日志 公共判断条件
     * @param $lists
     * @param $conditions
     * @return mixed
     */
    private function allWhere($lists,$conditions){
        if (isset($conditions['user_id']) && !empty($conditions['user_id'])) {
            $lists->where('user_id', $conditions['user_id']);
        }
        if (isset($conditions['assets_name']) && !empty($conditions['assets_name'])) {
            $lists->where('assets_name', $conditions['assets_name']);
        }
        if (isset($conditions['assets_type']) && !empty($conditions['assets_type'])) {
            $lists->where('assets_type', $conditions['assets_type']);
        }
        if (isset($conditions['change_type']) && !empty($conditions['change_type'])) {
            $lists->where('change_type', $conditions['change_type']);
        }
        if (isset($conditions['start_time']) && !empty($conditions['start_time']) && isset($conditions['end_time']) && !empty($conditions['end_time'])) {
            $lists->whereBetween('created_at', [$conditions['start_time'],$conditions['end_time']]);
        }else{
            if(isset($conditions['start_time']) && !empty($conditions['start_time'])){
                $lists->where('created_at','>',$conditions['start_time']);
            }elseif(isset($conditions['end_time']) && !empty($conditions['end_time'])){
                $lists->where('created_at','<',$conditions['end_time']);
            }
        }
        return $lists;
    }

    /**
     * Todo:: 查询数据
     * @param $lists
     * @param array $select
     * @return mixed
     */
    private function allSelect($lists,$select=[]){
        if($select){
            $lists->select($select);
        }else{
            $lists->select('*');
        }
        return $lists;
    }

    /**
     * Todo:: 全部资产日志列表
     * @param array $conditions
     * @param int $page
     * @param int $pageSize
     * @return \Illuminate\Database\Query\Builder|mixed
     */
    public function allLists($conditions=[],$page=1,$pageSize=20){
//        DB::connection()->enableQueryLog();
        $lists = $this->allTable($conditions);
        $lists = $lists->orderBy('created_at','desc')->paginate($pageSize,['*'],'page',$page);
//        echo '<pre>';
//        print_r(DB::getQueryLog());
//        exit;
        return $lists;
    }

    /**
     * Todo:: 获取所有的变动值
     * @param array $conditions
     * @return mixed
     */
    public function allChangeValueTotal($conditions=[]){
//        DB::connection()->enableQueryLog();
        $lists = $this->allTable($conditions,DB::raw('SUM(change_value) as change_value'));
        $total = $lists->sum('change_value');
//        echo '<pre>';
//        print_r(DB::getQueryLog());
//        exit;
        return $total;
    }

}
